package com.anonymous.community.api;

import android.content.Context;

import com.anonymous.community.utils.TokenManager;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ApiClient {
    
    // 根据API文档，基础URL为 /v1/api
    // TODO: 替换为实际的服务器地址
    private static final String BASE_URL = "http://47.97.98.126:8080/";
    
    // 根据API文档要求的User-Agent
    private static final String USER_AGENT = "Mozilla/5.0 cn.kicsy.niyan/2025.10.27; API/1.0 (KHTML, like Gecko)";
    
    private static Retrofit retrofit = null;
    private static ApiService apiService = null;
    private static Context appContext;

    /**
     * 初始化ApiClient
     */
    public static void init(Context context) {
        appContext = context.getApplicationContext();
    }

    public static Retrofit getClient() {
        if (retrofit == null) {
            // 创建日志拦截器
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            // 创建OkHttpClient
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(new UserAgentInterceptor())
                    .addInterceptor(new AuthInterceptor())
                    .addInterceptor(loggingInterceptor)
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .build();

            // 创建Retrofit实例
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }

    public static ApiService getApiService() {
        if (apiService == null) {
            apiService = getClient().create(ApiService.class);
        }
        return apiService;
    }

    /**
     * User-Agent拦截器
     * 根据API文档要求，所有请求必须携带指定的User-Agent
     */
    private static class UserAgentInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request requestWithUserAgent = originalRequest.newBuilder()
                    .header("User-Agent", USER_AGENT)
                    .build();
            return chain.proceed(requestWithUserAgent);
        }
    }

    /**
     * 认证拦截器
     * 自动为需要认证的请求添加Authorization header
     */
    private static class AuthInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            
            // 如果请求已经包含Authorization header，则不添加
            if (originalRequest.header("Authorization") != null) {
                return chain.proceed(originalRequest);
            }
            
            // 从TokenManager获取token
            if (appContext != null) {
                String token = TokenManager.getToken(appContext);
                if (token != null && !token.isEmpty()) {
                    Request requestWithAuth = originalRequest.newBuilder()
                            .header("Authorization", "Bearer " + token)
                            .build();
                    return chain.proceed(requestWithAuth);
                }
            }
            
            return chain.proceed(originalRequest);
        }
    }
}
